<?php
/**
 * Created by PhpStorm.
 * User: nightelf
 * Date: 2020/1/14
 * Time: 15:03
 */

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;

class WorkmanAssignmentModel1
{
    const TABLE = 'workman_assignment';

    public function group(array $data){
        return DB::table(self::TABLE)
            ->leftJoin('group as g','g.id','=',self::TABLE.'.groupId')
            ->where(function ($query) use ($data){
                if (!empty($data['projectId'])){
                    $query->where(self::TABLE.'.projectId',$data['projectId']);
                }
                if (!empty($data['sectionId'])){
                    $query->where(self::TABLE.'.sectionId',$data['sectionId']);
                }
                if (!empty($data['professionId'])){
                    $query->where(self::TABLE.'.professionId',$data['professionId']);
                }
                if (!empty($data['startTime']) && !empty($data['endTime'])){
                    $query->whereBetween('g.createTime',[$data['startTime'],$data['endTime']]);
                }
            })
            ->groupBy(self::TABLE.'.groupId')
            ->select('g.id','g.name')
            ->get()->toArray();
    }

    public function lists(array $data)
    {
        return DB::table(self::TABLE)
            ->leftJoin('assignment as a','a.id','=',self::TABLE.'.assignmentId')
            ->leftJoin('assignment_label as al','al.id','=','a.labelId')
            ->leftJoin('unit as u','u.id','=','a.unitId')
            ->leftJoin('admin','admin.id','=',self::TABLE.'.adminId')
            ->where(function($query) use ($data){
                $query->where(self::TABLE.'.projectId',$data['projectId'])
                ->where(self::TABLE.'.sectionId',$data['sectionId'])
                ->where(self::TABLE.'.professionId',$data['professionId'])
                ->where(self::TABLE.'.groupId',$data['groupId']);
                if (isset($data['batch']) && $data['batch'] !== ''){
                    $query->where(self::TABLE.'.batch',$data['batch']);
                }
                if (!empty($data['startTime']) && !empty($data['endTime'])){
                    $query->whereBetween('completeTime',[$data['startTime'],$data['endTime']]);
                }
            })
            ->select(self::TABLE.'.*','a.name as assignmentName','a.labelId','al.name as labelName','u.name as unitName','admin.name as adminName')
            ->get()->toArray();
    }

    /**
     * @param array $data
     * @return int
     */
    public function getBatch(array $data)
    {
        $result = DB::table(self::TABLE)
            ->where(self::TABLE.'.projectId',$data['projectId'])
            ->where(self::TABLE.'.sectionId',$data['sectionId'])
            ->where(self::TABLE.'.groupId',$data['groupId'])
            ->max('batch');
        if (!is_int($result)){
            $result = 0;
        }
        return $result;
    }
}